<template>
  <div class="project-page">
    <Drawer
      direction="left"
      ref="drawerLeft"
      class="drawer-root"
      @on-off="handleHide">
      <div class="module-container" v-for="(item, index) in leftComps" :key="index">
        <component v-if="item.hasShow" v-bind:is="item.component"></component>
      </div>
    </Drawer>
    <Drawer
      direction="right"
      ref="drawerRight"
      class="drawer-root"
      @on-off="handleHide">
      <div class="module-container" v-for="(item, index) in rightComps" :key="index">
        <component v-if="item.hasShow" v-bind:is="item.component" direction="right"></component>
      </div>
    </Drawer>
    <div v-if="projectId === 'project0007'" :class="['milestone-node', hasShowSearchBar ? 'hide' : 'show']">
      <milestone-node></milestone-node>
    </div>

    <div v-if="menuId === '1'" class="bimface-container">
      <div class="mask"></div>
      <!--bimface主视图-->
      <bim-face-pro
        v-if="bimfaceMainShow"
        ref="bimfaceMain"
        :loaderOptions="loaderOptions"
        :webAppOptions="webAppOptions"
        :viewAddedFn="handleViewLoad">
      </bim-face-pro>
    </div>

    <div v-if="menuId === '2'" class="bimface-container">
      <img class="main-img" :src="picItem.url" alt="">
    </div>

    <div v-if="menuId === '3'"  class="bimface-container">
      <iframe :src="vrItem.projectPath" width="100%" height="100%"></iframe>
    </div>

    <div v-if="menuId === '4'" class="bimface-container">
      <front-map :hasShowSearchBar="hasShowSearchBar"></front-map>
    </div>

    <div class="menu-bnts">
      <el-dropdown v-if="modelList.length" @command="(v) => handleCommand(v, '1')">
        <div :class="['btn', menuId === '1' ? 'active' : '']">
          BIM模型<i class="el-icon-arrow-down el-icon--right"></i>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="item in modelList" :command="item" :key="item.id">
            {{ item.projectTitel }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown v-if="picList.length" @command="(v) => handleCommand(v, '2')">
        <div :class="['btn', menuId === '2' ? 'active' : '']">
          场地图片<i class="el-icon-arrow-down el-icon--right"></i>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="item in picList" :command="item" :key="item.id">
            {{ item.projectTitel }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown v-if="vrList.length" @command="(v) => handleCommand(v, '3')">
        <div :class="['btn', menuId === '3' ? 'active' : '']">
          VR展示<i class="el-icon-arrow-down el-icon--right"></i>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="item in vrList" :command="item" :key="item.id">
            {{ item.projectTitel }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <div
        v-if="!emptyCommon"
        :class="['btn', menuId === '4' ? 'active' : '']"
        @click="handleCommand(null, '4')">
        地图影像
      </div>
    </div>
  </div>
</template>

<script>
import Drawer from '@/components/public/Drawer';
import BimFacePro from '@/components/bimface/project';
import Overview from '@/components/project/Overview';
import Units from '@/components/project/Units';
import Progress from '@/components/project/Progress';
import Production from '@/components/project/Production';
import Weather from '@/components/project/Weather';
import PersonnelInfo from '@/components/project/PersonnelInfo';
import TowerCrane from '@/components/project/TowerCrane';
import VideoMonitoring from '@/components/project/VideoMonitoring';
import Security from '@/components/project/Security';
import Quality from '@/components/project/Quality';
import monthNode from '@/components/project/front/monthNode';
import MilestoneNode from '@/components/project/front/MilestoneNode';
import QualityClosedLoop from '@/components/project/front/QualityClosedLoop';
import SecurityClosedLoop from '@/components/project/front/SecurityClosedLoop';
import frontMap from '@/components/project/front/frontMap';

export default {
  name: 'projectIndex',
  components: {
    BimFacePro,
    Drawer,
    Units,
    Progress,
    Production,
    Overview,
    Weather,
    PersonnelInfo,
    TowerCrane,
    VideoMonitoring,
    MilestoneNode,
    frontMap
  },
  data() {
    return {
      menuId: '1',
      // 模块配置是否为空
      emptyCommon: false,
      // bimface主模型配置
      loaderOptions: {
        viewToken: ''
      },
      fileId: '',
      viewer: null,
      bimfaceMainShow: false,
      hasShowSearchBar: false,
      // bimface WebApplication3D的配置
      webAppOptions: {
        // 取消 轮廓框
        enableBorderLine: false
      },
      leftComps: [],
      rightComps: [],
      compOptions: {
        Overview: {
          id: '1',
          hasShow: false,
          component: Overview
        },
        Units: {
          id: '2',
          hasShow: false,
          component: Units
        },
        Weather: {
          id: '3',
          hasShow: false,
          component: Weather
        },
        PersonnelInfo: {
          id: '4',
          hasShow: false,
          component: PersonnelInfo
        },
        Progress: {
          id: '5',
          hasShow: false,
          component: Progress
        },
        TowerCrane: {
          id: '6',
          hasShow: false,
          component: TowerCrane
        },
        Production: {
          id: '7',
          hasShow: false,
          component: Production
        },
        VideoMonitoring: {
          id: '8',
          hasShow: false,
          component: VideoMonitoring
        },
        Security: {
          id: '9',
          hasShow: false,
          component: Security
        },
        Quality: {
          id: '10',
          hasShow: false,
          component: Quality
        },
        monthNode: {
          id: '11',
          hasShow: false,
          component: monthNode
        },
        QualityClosedLoop: {
          id: '12',
          hasShow: false,
          component: QualityClosedLoop
        },
        SecurityClosedLoop: {
          id: '13',
          hasShow: false,
          component: SecurityClosedLoop
        },
      },
      BimConfig: {},
      mapConfig: {},
      // 模型数据
      modelItem: {},
      modelList: [],
      // 图片数据
      picItem: {},
      picList: [],
      // VR展示
      vrItem: {},
      vrList: [],
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
  },
  async created() {
    await Promise.all([
      this.getTableData(),
      this.generateModule()
    ]);
  },
  methods: {
    handleCommand(val, type) {
      this.menuId = type;
      if (type === '1') {
        const { projectPath } = this.modelItem;
        if (!projectPath || val.projectPath !== projectPath) {
          this.modelItem = { ...val };
          this.getViewToken(val.projectPath);
        }
      } else if (type === '2') {
        this.picItem = { ...val };
      } else if (type === '3') {
        this.vrItem = { ...val };
      }
    },
    // 获取模型管理列表数据
    async getTableData(options = {}) {
      const params = {
        projectId: this.projectId,
        pageFlag: false,
        ...options
      };
      const { success, data: { data }} = await this.$Model.getCommonList(params);
      if (success && data) {
        const { list = [] } = data;
        // projectType: 1新闻；2公告；3轮播图；4图片、视频管理；5模型管理；6倾斜摄影，7 vR地址
        this.modelList = list.filter(v => ['5', '6'].includes(v.projectType));
        this.vrList = list.filter(v => v.projectType === '7');
        this.picList = list
          .filter(v => v.projectType === '4')
          .map(item => ({
            ...item,
            url: this.$checkUrl(item.projectPath)
          }));
        if (this.modelList.length) {
          this.menuId = '1';
          this.modelItem = { ...this.modelList[0] };
          this.getViewToken(this.modelItem.projectPath);
          return;
        }
        if (this.picList.length) {
          this.menuId = '2';
          this.picItem = { ...this.picList[0] };
          return;
        }
        if (this.vrList.length) {
          this.menuId = '3';
          this.vrItem = { ...this.vrList[0] };
          return;
        }
        this.emptyCommon = true;
        this.menuId = '4';
      }
    },
    // 获取项目配置详情
    async getViewToken(fileId) {
      if (!fileId) return;
      const { success, data } = await this.$Model.getViewToken({
        fileId
      });
      if (success && data.data) {
        this.bimfaceMainShow = true;
        await this.getBimConfig({
          viewToken: data.data,
          fileId
        });
        this.loaderOptions = {
          viewToken: data.data
        };
      }
    },
    // 获取列表数据
    async getCommonList(params = {}) {
      return await this.$Model.getCommonList({
        projectId: this.projectId,
        pageFlag: false,
        ...params
      });
    },
    // 获取模型配置
    async getBimConfig({ fileId }) {
      const { success, data: { data }} = await this.$Model.getBimConfig({
        pageFlag: false,
        fileId
      });
      if (success && data) {
        const list = data.list || [];
        this.BimConfig = list[0] || {};
      }
    },
    handleHide(value) {
      this.$refs.drawerLeft.trigger(value);
      this.$refs.drawerRight.trigger(value);
      this.hasShowSearchBar = !value;
    },
    // 地图初始化
    initMap() {
      /* eslint-disable */
      const mapOptions = {
        datasourcesControl: true
      };
      this.mapApp = new T.Map('main-map', mapOptions);
      const { lat = 39.89945, lng = 116.40969 } = this.projectLatlng;
      this.mapApp.centerAndZoom(new T.LngLat(lng, lat), this.zoom);
      this.geocoder = new T.Geocoder();
      this.ctrl = new T.Control.MapType();
      this.mapApp.addControl(this.ctrl);
    },
    /**
     * 主模块bimface图层加载完成
     * @param viewer: bimface实例
     * @param viewApp
     */
    handleViewLoad(viewer, viewApp) {
      this.viewer = viewer;
      this.setMapSource(viewer, viewApp);
    },
    setMapSource(viewer, viewApp) {
      /* eslint-disable */
      const {
        lng = 0,
        lat = 0,
        pointX = 0,
        pointY = 0,
        height = 0,
        radian = 0
      } = this.BimConfig;
      const mapConfig = new Glodon.Bimface.Plugins.TileMap.MapConfig();
      mapConfig.viewer = viewer;
      // 设置模型载入的基点
      mapConfig.basePoint = {
        x: pointX,
        y: pointY
      };
      // 设置模型载入基点所对应的经纬度（WGS84）
      // mapConfig.modelPosition = [lng, lat];
      mapConfig.modelPosition = [119.75946981717281, 30.381455410645202];
      // 设置模型的旋转弧度值
      mapConfig.modelRotationZ = radian;
      // mapConfig.modelRotationZ = 22 * Math.PI / 180;
      // 设置模型零零标高对应的高程值，单位为米
      mapConfig.modelAltitude = height;
      this.mapConfig = mapConfig;
      // 构造地图对象
      this.mapApp = new Glodon.Bimface.Plugins.TileMap.Map(mapConfig);
      // 设置地图类型为天地图的影像底图
      this.mapApp.setMapSource({
        url: 'http://t0.tianditu.gov.cn/img_w/wmts?tk=ebbfd0ea032ff7f43004fdbe059fe4cf',
        provider: 'Tianditu',
        credit: Glodon.Bimface.Common.Credit.Tianditu
      });
      // 渲染场景
      viewer.render();
    },
    /**
     * 获取模块配置
     */
    async generateModule() {
      const { success, data: { data }} = await this.$Model.generateModule({
        projectId: this.projectId,
      });
      if (success && Array.isArray(data)) {
        const compKeys = Object.keys(this.compOptions);
        const leftComps = [];
        const rightComps = [];
        data.forEach(item => {
          const { moduleSort, moduleCode } = item;
          let currentItem = { ...item };
          const currentKey = compKeys.find(key => {
            const { id } = this.compOptions[key];
            return id === moduleCode;
          });
          if (currentKey) {
            currentItem = this.compOptions[currentKey];
            currentItem.hasShow = true;
          }
          const residue = moduleSort % 2;
          if (residue === 0) {
            rightComps[(moduleSort / 2) - 1] = currentItem;
            return;
          }
          leftComps[(moduleSort - 1) / 2] = currentItem;
        });
        if (this.projectId === 'project0007') {
          leftComps.splice(3, 1);
          rightComps.splice(3, 1);
        }
        this.leftComps = leftComps;
        this.rightComps = rightComps;
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "../../assets/styles/main";
@import "../../assets/styles/dialog";

.project-page {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .menu-bnts {
    position: absolute;
    z-index: 99;
    width: 660px;
    height: 50px;
    left: calc(50% - 330px);
    bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: transparent;
    .btn {
      width: 120px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: $lightLinearG;
      color: #fff;
      margin: 0 20px;
      cursor: pointer;
      border-radius: 30px;
      box-shadow: 0 1px 4px 0 $lightBtnBg;
      transition: background .2s;
      font-size: 16px;
      &.active {
        background: $linearG;
        font-weight: 500;
      }
    }
  }
  .bimface-container {
    width: 100%;
    height: 100%;
    position: relative;
    background: linear-gradient(0deg, rgb(246, 250, 255) 10%, rgb(214, 224, 235) 70%);
    .main-img {
      width: 100%;
      height: 100%;
    }
    .mask {
      pointer-events: none;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 1;
    }
    /deep/ .bimface-project {
      #bimface {
        .bf-toolbar.bf-toolbar-bottom {
          bottom: 70px;
        }
      }
    }
  }
  .drawer-root {
    padding-top: 20px;
    .module-container {
      width: 100%;
      height: 25%;
    }
  }
  @keyframes warn {
    to {
      opacity: .6;
    }
  }
  /deep/ #bimface .bf-drawable-lead-label {
    color: #000;
  }


  .milestone-node {
    width: 100%;
    height: 25%;
    position: absolute;
    z-index: 9;
    left: 0;
    bottom: 0;
    background: transparent;
    transform: translateY(100%);
    transition: transform .3s, opacity .4s;
    &.show {
      opacity: 1;
      transform: translateY(0%);
    }
  }
}
</style>
